﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity;
using static LH.Model.ST.ST_Rdrecord11;

namespace Yonyou.U8.BO
{

    public class TransVouchVM : ST_TransVouch
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";


        public TransVouchVM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }



        public RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject($"当前单据号{this.head.cTVCode}已存在");
                } 
                foreach (Body body in bodies)
                {
                    body.editprop = "A";
                }

                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败：" + cRe);
                }

                //调拨单，额外增加其他出入库单的处理
                if (!TransVouchDALCO.AddVerifyTransvouch(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "delete", out cerr2);
                    }

                    return DBService.ReErrObject("新增失败：" + err);
                } 
                else
                {

                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        //不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                        //if (!bWMS)
                        //{

                        //    if (ccode != head.cTVCode && head.cTVCode != WMSPara.rdTVCode)
                        //    {
                        //        //单据编码选项判断
                        //        string sqlrep = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0304'");
                        //        int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sqlrep));
                        //        if (iRepeat == 1)
                        //        {
                        //            string cerr2 = "";
                        //            TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                        //            return DBService.ReOKObject("单据已生成，重复");
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                        //    string cParentid = head.cDefine10;
                        //    if (!string.IsNullOrEmpty(cParentid))
                        //    {
                        //        //检查cParentid 是否存在
                        //        string sqlcx = string.Format(@"select count(*) sl from transvouch a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                        //        int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                        //        if (icntUniq > 0)
                        //        {
                        //            TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out _);
                        //            return DBService.ReOKObject("之前单据已生成，重复");
                        //        }
                        //    } 
                        //}

                        DateTime dDate = DbHelper.GetDbDate(head.dTVDate);
                        int iid = DbHelper.GetDbInt(id);
                        db.Updateable<TransVouch>()
                .SetColumns(u => new TransVouch()
                {
                    dVerifyDate = dDate,
                    cVerifyPerson = head.cMaker
                })
                .Where(u => u.ID == iid)
                .ExecuteCommand();

                        string sql = string.Format("select id from rdrecord09 where cbustype='调拨出库' and  cbuscode = '{0}'", ccode);
                        string iid9 = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                        string cerr = "";
                        if (!Rdrecord09DALCO.VerifyRdrecord09(iid9, xmlConfig, "verify", out cerr))
                        {
                            //删除掉调拨单
                            string cerr2 = "";
                            TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                            throw new Exception(cerr);
                        };

                        sql = string.Format("select id from rdrecord08 where cbustype='调拨入库' and  cbuscode = '{0}'", ccode);
                        string iid8 = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                        if (!Rdrecord08DALCO.VerifyRdrecord08(iid8, xmlConfig, "verify", out cerr))
                        {
                            // 删除掉调拨单
                            string cerr2 = "";
                            TransVouchDALCO.VerifyTransvouch(id, xmlConfig, "unverify,delete", out cerr2);
                            throw new Exception(cerr);
                        }

                    }


                }
                //生成的id赋值
                head.ID = id;
                head.cTVCode = ccode;
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }



        public string GetAddInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cInvCode;
                        WMS_GetSource source = new WMS_GetSource();
                        ////根据是否有调拨申请单号判断
                        //if ( head.csource=="1")
                        //{

                        //    //int iSourceid = DbHelper.GetDbInt(bodies[i].iTRIds);
                        //    source = db.Queryable<ST_AppTransVouchs>()
                        //    .InnerJoin<ST_AppTransVouch>((a, b) => a.ID == b.ID && a.cDefine31 == bodies[i].cDefine32)
                        //    .Select((a, b) => new WMS_GetSource
                        //    {
                        //        ID = b.ID,  
                        //        Autoid = a.autoID,
                        //        cCode = b.cTVCode,
                        //        cDepCode = b.cODepCode,
                        //        //过渡，取调入部门
                        //        cCusCode = b.cIDepCode,
                        //        //过渡，取收发类别。
                        //        cDefine1 = b.cORdCode,
                        //         cDefine2 =b.cIRdCode,
                        //        cPersonCode = b.cPersonCode, 
                        //        dDate = b.dTVDate,
                        //        cInvCode = a.cInvCode,
                        //        cUnitID = a.cAssUnit,
                        //        cMemo = b.cTVMemo,
                        //        cbMemo = a.cbMemo,
                        //        iChangeRate = a.iinvexchrate,  
                        //        cItem_class = a.cItem_class,
                        //        cItemCode = a.cItemCode,
                        //        cItemName = a.cName,
                        //        cItemCName = a.cItemCName
                        //    }).First();
                        //    if (source == null)
                        //    {
                        //        return string.Format("第{0}行调拨申请单查询不到", (i + 1).ToString());
                        //    }
                        //}
                        //else
                        //{
                        //    //没有处理来料检验单
                        //    return "无来源单据，无需处理";

                        //}
                        //if (i == 0 && source != null)
                        //{
                        //    head.cODepCode = source.cDepCode;
                        //    head.cIDepCode = source.cCusCode;  //这个是过渡的

                        //    //如果调拨申请填写了出入库类别，使用这个
                        //    if ( !string.IsNullOrWhiteSpace(source.cDefine1))
                        //    {
                        //        head.cORdCode = source.cDefine1;
                        //    }
                        //    if (!string.IsNullOrWhiteSpace(source.cDefine2))
                        //    {
                        //        head.cIRdCode = source.cDefine2;
                        //    }
                        //    head.cTVMemo = source.cMemo;
                        //    head.cTranRequestCode = source.cCode;

                        //}

                        //if (source.cInvCode != bodies[i].cInvCode)
                        //{
                        //    return string.Format("第{0}行申请物料和{1}不一致", (i + 1).ToString(), bodies[i].cInvCode);
                        //}

                        //bodies[i].iTRIds = DbHelper.GetDbString(source.Autoid);
                        ////没有检查自由项,是否和来源订单一样
                        //bodies[i].cInvCode = source.cInvCode;
                        ////调拨单，没有价格 
                    
                        //bodies[i].cItemCName = source.cItemCName;
                        //bodies[i].cItemCode = source.cItemCode;
                        //bodies[i].cItem_class = source.cItem_class;
                        //bodies[i].cName = source.cItemName;
                        //bodies[i].cAssUnit = source.cUnitID;
                        InvProperty invProperty = new InventoryVM().GetInvProperty(bodies[i].cInvCode, bodies[i].dMadeDate, bodies[i].dDisDate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行订单物料{1}不存在", (i + 1).ToString(), bodies[i].cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cAssUnit))
                            {
                                bodies[i].cAssUnit = invProperty.cSTComUnitCode;
                            }

                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(source.iChangeRate)))
                            {
                                bodies[i].iinvexchrate = invProperty.iChangRate;
                            }
                            else
                            {
                                bodies[i].iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                            }
                            if (DbHelper.GetDbdecimal(bodies[i].iinvexchrate) != 0)
                            {
                                bodies[i].iTVNum = (DbHelper.GetDbdecimal(bodies[i].iTVQuantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }
                        }

                        //是否批次管理
                        if (!invProperty.bInvBatch)
                        {
                            bodies[i].cTVBatch = "";
                        }
                        else if (string.IsNullOrEmpty(bodies[i].cTVBatch))
                        {
                            return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        }
                        //自由项，未处理

                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            if (string.IsNullOrEmpty(bodies[i].dMadeDate) && string.IsNullOrEmpty(bodies[i].dDisDate))
                            {
                                return string.Format("第{0}行物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                            else
                            {
                                bodies[i].dDisDate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].iMassDate = DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cMassUnit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dExpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iExpiratDateCalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }


                        } 
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
             
            return "ok";
        }


        /// <summary>
        /// 检查单据号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from transvouch where ctvcode='{0}' ", head.cTVCode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));
                
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }


       

        public RetModel2 UnverifyDelete()
        {
            //审核失败后，检查是否有其他入库单生成，如果有，则删除
            string cerr2 = "";
            string ID = "";
            if (!Exists(ref ID))
            {
                return DBService.ReOKObject($"当前单据号{head.cTVCode}已删除");
            }

            if (!string.IsNullOrEmpty(ID))
            {
                RdRecord08VM rdRecord08VM = new RdRecord08VM(new ST_Rdrecord08.Head(), new List<ST_Rdrecord08.Body>());
                string id8 = "";
                if (rdRecord08VM.GetIdByTVCode(head.cTVCode,ref id8))
                {
                    rdRecord08VM.head.id = id8;
                   RetModel2 ret8 =  rdRecord08VM.Unverify();
                    if (ret8.code != 200)
                    {
                        return DBService.ReErrObject("弃审调拨单生成的其他入库单失败:" + ret8.message);
                    }
                }

                string id9 = "";
                RdRecord09VM rdRecord09VM = new RdRecord09VM(new ST_Rdrecord09.Head(), new List<ST_Rdrecord09.Body>());
                if (rdRecord09VM.GetIdByTVCode(head.cTVCode, ref id9))
                {
                    rdRecord09VM.head.id = id9;
                    RetModel2 ret9 = rdRecord09VM.Unverify();
                    if (ret9.code != 200)
                    {
                        return DBService.ReErrObject("弃审调拨单生成的其他出库单失败:" + ret9.message);
                    }
                }

                if (!TransVouchDALCO.VerifyTransvouch(ID, xmlConfig, "unverify,delete", out cerr2))
                {
                    return DBService.ReErrObject("删除失败：" + cerr2);
                }
            }

            return DBService.ReOKObject("删除完成");

        }


        /// <summary>
        /// 新增实体，根据申请单
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public TransVouchVM GetAddEntity(API_TransVouch obj, ref string cErr)
        {

            try
            { 
                ST_TransVouch.Head head = new ST_TransVouch.Head
                {
                    bWireless = "1",
                    csource = "1",  
                    itransflag = "正向",
                    dTVDate = obj.dDate,
                    cIWhCode = obj.cIWhCode,
                    cOWhCode = obj.cOWhCode, 
                    cORdCode = obj.cORdCode,
                    cIRdCode = obj.cIRdCode, 
                    cMaker = obj.cMaker,
                //rdHead.cVerifyPerson = scanBarcodes.cUserName;
                cTVCode = obj.cTVCode,
                iPrintCount = "0",  
                cDefine1 = obj.cDefine1,
                  cDefine2 = obj.cDefine2,
                    cDefine3 = obj.cDefine3,
                    cDefine4 = obj.cDefine4,
                    cDefine5 = obj.cDefine5,
                    cDefine6 = obj.cDefine6,
                    cDefine7 = obj.cDefine7,
                    cDefine8 = obj.cDefine8,
                    cDefine9 = obj.cDefine9,
                    cDefine10 = obj.cDefine10,
                    cDefine11 = obj.cDefine11,
                    cDefine12 = obj.cDefine12,
                    cDefine13 = obj.cDefine13,
                    cDefine14 = obj.cDefine14,
                    cDefine15 = obj.cDefine15,
                    cDefine16 = obj.cDefine16,
                };
              
                List<LH.Model.ST.ST_TransVouch.Body> bodies = new List<LH.Model.ST.ST_TransVouch.Body>();

                 
               if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_TransVouch.Body body = new ST_TransVouch.Body
                            {

                                cInvCode = item.cInvCode,
                                //cfree1 = item.cFree1,
                                //cfree2 = item.cFree2,
                                //cfree3 = item.cFree3,
                                //cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iTVQuantity = DbHelper.GetDbString(item.iQuantity),
                                iTVNum = DbHelper.GetDbString(item.iNum),
                                cTVBatch = item.cBatch,
                                 coutposcode= item.cOPosCode,
                                 cinposcode = item.cIPosCode,
                               
                                cbMemo = item.cBMemo,
                                cItemCode = item.cItemCode,
                                cItemCName = item.cItem_Name,
                                cItem_class = item.cItem_Class,
                                //33自定义项作为mes行id
                                cDefine31 = item.cRowId,
                                cDefine32 = item.cDefine32,
                                //从22 写到37
                                cDefine22 = item.cDefine22,
                                cDefine23 = item.cDefine23,
                                cDefine24 = item.cDefine24,
                                cDefine25 = item.cDefine25,
                                cDefine26 = item.cDefine26,
                                cDefine27 = item.cDefine27,
                                cDefine28 = item.cDefine28,
                                cDefine29 = item.cDefine29,
                                cDefine30 = item.cDefine30,
                                cDefine33 = item.cDefine33, 

                                cDefine34 = item.cDefine34,
                                cDefine35 = item.cDefine35,
                                cDefine36 = item.cDefine36,
                                cDefine37 = item.cDefine37

                            }; 

                            bodies.Add(body);
                        }
                    }
                }



                TransVouchVM model = new TransVouchVM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }

        /// <summary>
        /// 新增实体，根据申请单
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public TransVouchVM GetAddEntity_FromApp(API_TransVouch obj, ref string cErr)
        {

            try
            {
                ST_TransVouch.Head head = new ST_TransVouch.Head
                {
                    bWireless = "1",
                    csource = "1",  //调拨申请单
                    itransflag = "正向",
                    dTVDate = obj.dDate,
                    cIWhCode = obj.cIWhCode,
                    cOWhCode = obj.cOWhCode,
                    cORdCode = CanShu.RdTV09,
                    cIRdCode = CanShu.RdTV08,
                    cMaker = obj.cMaker,
                    //rdHead.cVerifyPerson = scanBarcodes.cUserName;
                    cTVCode = obj.cTVCode,
                    iPrintCount = "0",
                    cDefine1 = obj.cDefine1,
                    cDefine2 = obj.cDefine2,
                    cDefine3 = obj.cDefine3,
                    cDefine4 = obj.cDefine4,
                    cDefine5 = obj.cDefine5,
                    cDefine6 = obj.cDefine6,
                    cDefine7 = obj.cDefine7,
                    cDefine8 = obj.cDefine8,
                    cDefine9 = obj.cDefine9,
                    cDefine10 = obj.cDefine10,
                    cDefine11 = obj.cDefine11,
                    cDefine12 = obj.cDefine12,
                    cDefine13 = obj.cDefine13,
                    cDefine14 = obj.cDefine14,
                    cDefine15 = obj.cDefine15,
                    cDefine16 = obj.cDefine16,
                };
                if (obj.cSource == "调拨申请调拨")
                {
                    head.cTranRequestCode = obj.cTranRequestCode;   //来源单号 
                }
                List<LH.Model.ST.ST_TransVouch.Body> bodies = new List<LH.Model.ST.ST_TransVouch.Body>();


                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_TransVouch.Body body = new ST_TransVouch.Body
                            {

                                cInvCode = item.cInvCode,
                                //cfree1 = item.cFree1,
                                //cfree2 = item.cFree2,
                                //cfree3 = item.cFree3,
                                //cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iTVQuantity = DbHelper.GetDbString(item.iQuantity),
                                iTVNum = DbHelper.GetDbString(item.iNum),
                                cTVBatch = item.cBatch,
                                coutposcode = item.cOPosCode,
                                cinposcode = item.cIPosCode,

                                cbMemo = item.cBMemo,
                                cItemCode = item.cItemCode,
                                cItemCName = item.cItem_Name,
                                cItem_class = item.cItem_Class,
                                //33自定义项作为mes行id
                                cDefine31 = item.cRowId,
                                cDefine32 = item.cSoureRowId,
                                //从22 写到37
                                cDefine22 = item.cDefine22,
                                cDefine23 = item.cDefine23,
                                cDefine24 = item.cDefine24,
                                cDefine25 = item.cDefine25,
                                cDefine26 = item.cDefine26,
                                cDefine27 = item.cDefine27,
                                cDefine28 = item.cDefine28,
                                cDefine29 = item.cDefine29,
                                cDefine30 = item.cDefine30,
                                cDefine33 = item.cDefine33,

                                cDefine34 = item.cDefine34,
                                cDefine35 = item.cDefine35,
                                cDefine36 = item.cDefine36,
                                cDefine37 = item.cDefine37

                            };

                            bodies.Add(body);
                        }
                    }
                }



                TransVouchVM model = new TransVouchVM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }
        /// <summary>
        /// 传入json转换成 vm
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public TransVouchVM GetCodeEntity(API_TransVouch obj, ref string cErr)
        {

            try
            {

                ST_TransVouch.Head head = new ST_TransVouch.Head();
                head.cTVCode = obj.cTVCode;
                List<ST_TransVouch.Body> bodies = new List<ST_TransVouch.Body>();

                TransVouchVM model = new TransVouchVM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }
             
        }
        
         


    }
}
